//
//  ProvinceViewController.m
//  wtshoppingcite
//
//  Created by TW on 14-10-27.
//  Copyright (c) 2014年 TW. All rights reserved.
//

#import "ProvinceViewController.h"
#import <CoreLocation/CoreLocation.h>
#import "CitySectionModel.h"
@interface ProvinceViewController ()<CLLocationManagerDelegate>

@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) UILabel *locationLabel;
@property (nonatomic, strong) NSMutableArray *listContent;
@property (nonatomic, strong) NSMutableArray *citylistContent;

@end

@implementation ProvinceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setTitleView:@"选择城市"];
    
    _provinceArray = [[NSArray alloc]initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"area.plist" ofType:nil]];
    
    _citylistContent = [[NSMutableArray alloc] initWithCapacity:0];
    NSArray* otherArr = @[@"北京",@"上海",@"天津",@"重庆",@"澳门",@"香港"];
    for(NSString* str in otherArr){
        CitySectionModel* model = [[CitySectionModel alloc] init];
        model.cityName = str;
    }
    [self getAllCitys];
    [self createLocationInfoView];
    [self getUserLocationCity];
    
    // Do any additional setup after loading the view.
}

-(void)getAllCitys{
    for(int i = 0;i<_provinceArray.count;i++){
        if(i >3 && i<_provinceArray.count -3){
            NSArray* cityArray = [[_provinceArray objectAtIndex:i] objectForKey:@"cities"];
            for(int j = 0;j<cityArray.count;j++){
                
                NSString* city = [[cityArray objectAtIndex:j]objectForKey:@"city"];
                CitySectionModel* model = [[CitySectionModel alloc] init];
                model.cityName = city;
                [_citylistContent addObject:model];
            }
        }
    }
    
    [self sortData:_citylistContent];
//    NSLog(@"%@",_citylistContent);
}


- (void)sortData:(NSArray *)data
{
    // Sort data
    UILocalizedIndexedCollation *theCollation = [UILocalizedIndexedCollation currentCollation];
    for (CitySectionModel *model in _citylistContent) {
        NSInteger sect = [theCollation sectionForObject:model
                                collationStringSelector:@selector(cityName)];
        model.sectionNumber = sect;
    }
    
    NSInteger highSection = [[theCollation sectionTitles] count];
    NSMutableArray *sectionArrays = [NSMutableArray arrayWithCapacity:highSection];
    for (int i=0; i<=highSection; i++) {
        NSMutableArray *sectionArray = [NSMutableArray arrayWithCapacity:1];
        [sectionArrays addObject:sectionArray];
    }
    
    for (CitySectionModel *model in data) {
        [(NSMutableArray *)[sectionArrays objectAtIndex:model.sectionNumber] addObject:model];
    }
    
    if(_listContent == nil){
        _listContent = [NSMutableArray arrayWithCapacity:1];
    }
    for (NSMutableArray *sectionArray in sectionArrays) {
        NSArray *sortedSection = [theCollation sortedArrayFromArray:sectionArray
                                            collationStringSelector:@selector(cityName)];
        [_listContent addObject:sortedSection];
    }
    [self.cityListTable reloadData];
}

- (void)createLocationInfoView
{
    UIView *locationView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kToolBarHeight)];
    UIImageView *locationIcon = [[UIImageView alloc] initWithFrame:CGRectMake(10, 13, 12, 18)];
    locationIcon.image = [UIImage imageNamed:@"location.png"];
    [locationView addSubview:locationIcon];
    
    _locationLabel = [[UILabel alloc] initWithFrame:CGRectMake(locationIcon.right+10, 12, kWidth-54, 20)];
    _locationLabel.font = [UIFont systemFontOfSize:16.0f];
    _locationLabel.text = @"获取位置中...";
    [locationView addSubview:_locationLabel];
    self.cityListTable.tableHeaderView = locationView;
    
}

//定位当前用户所在城市
- (void)getUserLocationCity
{
    _locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
    if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
        [self.locationManager requestWhenInUseAuthorization];
    }
    [self.locationManager startUpdatingLocation];
}


#pragma mark - UITableViewDataSource & Delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //    return _provinceArray.count;
    return [[_listContent objectAtIndex:section] count];
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //    return _provinceArray.count;
    return [_listContent count];
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    //    cell.textLabel.text = _provinceArray[indexPath.row];
    //    cell.textLabel.numberOfLines = 2;
    CitySectionModel *model = (CitySectionModel *)[[_listContent objectAtIndex:indexPath.section]
                                                   objectAtIndex:indexPath.row];
    cell.textLabel.text = model.cityName;
    cell.textLabel.numberOfLines = 2;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}


- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    //    if (tableView == self.searchDisplayController.searchResultsTableView) {
    //        return nil;
    //    } else {
//    return [[NSArray arrayWithObject:UITableViewIndexSearch] arrayByAddingObjectsFromArray:
//            [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles]];
    return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
    //    }
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    //    if (tableView == self.searchDisplayController.searchResultsTableView) {
    //        return 0;
    //    } else {
    //        if (title == UITableViewIndexSearch) {
    //            [tableView scrollRectToVisible:self.searchDisplayController.searchBar.frame animated:NO];
    //            return -1;
    //        } else {

//    NSLog(@"%d",[[UILocalizedIndexedCollation currentCollation] sectionForSectionIndexTitleAtIndex:index-1]);
    return [[UILocalizedIndexedCollation currentCollation] sectionForSectionIndexTitleAtIndex:index];
    //        }
    //    }
}


- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    //    if (tableView == self.searchDisplayController.searchResultsTableView) {
    //        return nil;
    //    } else {
    if(section == 27)
        return nil;
    return [_listContent count] ? [[[UILocalizedIndexedCollation currentCollation] sectionTitles] objectAtIndex:section] : nil;
    //    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    //    if (tableView == self.searchDisplayController.searchResultsTableView)
    //        return 0;
    return _listContent.count ? tableView.sectionHeaderHeight : 0;
}


#pragma mark - Location Methods
// 错误信息
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    NSLog(@"error");
    _locationLabel.text = @"获取位置失败";
}

// 6.0 以上调用这个函数
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    
    if(locations.count == 0){
        return;
    }
    CLLocation *newLocation = locations[0];
    CLLocationCoordinate2D oldCoordinate = newLocation.coordinate;
    NSLog(@"旧的经度：%f,旧的纬度：%f",oldCoordinate.longitude,oldCoordinate.latitude);
    
    
    NSString *longitude =[NSString stringWithFormat:@"%f",oldCoordinate.longitude];
    NSString *latitude =[NSString stringWithFormat:@"%f",oldCoordinate.latitude];
    [RegisterHelper shareHelper].longitude = longitude;
    [RegisterHelper shareHelper].latitude = latitude;
    
    //    CLLocation *newLocation = locations[1];
    //    CLLocationCoordinate2D newCoordinate = newLocation.coordinate;
    //    NSLog(@"经度：%f,纬度：%f",newCoordinate.longitude,newCoordinate.latitude);
    
    // 计算两个坐标距离
    //    float distance = [newLocation distanceFromLocation:oldLocation];
    //    NSLog(@"%f",distance);
    
    [manager stopUpdatingLocation];
    
    //------------------位置反编码---5.0之后使用-----------------
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    
    [geocoder reverseGeocodeLocation:newLocation
                   completionHandler:^(NSArray *placemarks, NSError *error){
                       [self analyzePlaceMarks:placemarks];
                   }];
    
}

// 6.0 调用此函数
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    NSLog(@"%@", @"ok");
    [manager stopUpdatingLocation];
    
    //------------------位置反编码---5.0之后使用-----------------
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:newLocation
                   completionHandler:^(NSArray *placemarks, NSError *error){
                       
                       [self analyzePlaceMarks:placemarks];
                   }];
    
    
    
}

- (void)analyzePlaceMarks:(NSArray *)placemarks
{
    for (CLPlacemark *place in placemarks) {
        NSLog(@"name,%@",place.name);                       // 位置名
        //                           NSLog(@"thoroughfare,%@",place.thoroughfare);       // 街道
        //                           NSLog(@"subThoroughfare,%@",place.subThoroughfare); // 子街道
        //                           NSLog(@"locality,%@",place.locality);               // 市
        //                           _locationLabel.text = place.locality;
        //                           NSLog(@"subLocality,%@",place.subLocality);         // 区
        //                           NSLog(@"country,%@",place.country);                 // 国家
        
        NSString *locationStr = [NSString stringWithFormat:@"%@ %@(我的位置)",place.country,place.locality];
        _locationLabel.text = locationStr;
    }
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    ;
}


- (void)viewWillDisappear:(BOOL)animated
{
    
    [super viewWillDisappear:animated];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
